//
//  SceneViewController.m
//  YSSmartHome
//
//  Created by Yahaong on 16/8/10.
//  Copyright © 2016年 yahaong. All rights reserved.
//

#import "SceneViewController.h"
#import "ZTLinkageUtil.h"
#import "ZTLinkageData.h"
#import "MQTTSessionManager.h"
#import "MQTTCoverTool.h"
#import "SceneCell.h"
#import "DataManager.h"
#import "SceneAddController.h"
#import "NoSceneView.h"
#import "SceneEditController.h"
#import "UIBarButtonItem+Extension.h"
#import "MeViewController.h"
#import "XAIGateway.h"

static NSString *const sceneCellReuseIdentifier = @"sceneCellReuseIdentifier";

@interface SceneViewController ()
<
UICollectionViewDelegate,
UICollectionViewDataSource,
DataManagerRefreshDelegate
>
@property (nullable, nonatomic, strong) NoSceneView *noSceneView;
@property (nullable, nonatomic, strong) UICollectionView *collectionView;
@property (nullable, nonatomic, strong) UICollectionViewFlowLayout *flowLayout;
@property (nullable, nonatomic, strong) NSMutableArray <ZTLinkage *> *linkages;
@property (nonatomic, assign) LinkageNum currentLinkmum;
@property (nullable, nonatomic, strong) NSIndexPath *originalIndexPath;
@property (nullable, nonatomic, strong) UINavigationBar* navigationBar;
@property (nullable, nonatomic, strong) UINavigationItem *titleItem;
@end

@implementation SceneViewController

#pragma mark - life cycle
- (void)dealloc
{
    debugLogInfo(@"SceneViewController dealloc");
    [kDataManager removeLinkageRefreshDelegate:self];
    [kDataManager removeGatewayRefreshDelegate:self];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self initSubviews];
    [self initLinkage];
    [self addGesture];
    [kDataManager addLinkageRefreshDelegate:self];
    [kDataManager addGatewayRefreshDelegate:self];
}
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:YES];
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}
#pragma mark - event response
- (void)tapGestureHandle:(UITapGestureRecognizer *)tap
{
    if (self.originalIndexPath)
    {
        SceneCell *originalCell = (SceneCell *)[self.collectionView cellForItemAtIndexPath:self.originalIndexPath];
        originalCell.isEditOrDel = NO;
        self.originalIndexPath = nil;
    }
    else
    {
        NSIndexPath *currentIndex = [self.collectionView indexPathForItemAtPoint:[tap locationOfTouch:0 inView:self.collectionView]];
        if (currentIndex)
        {
            [self collectionView:self.collectionView didSelectItemAtIndexPath:currentIndex];
        }
    }
}
- (void)longPressedGestureHandle:(UILongPressGestureRecognizer *)longPressGesture
{
    if (longPressGesture.state == UIGestureRecognizerStateBegan)
    {
        NSIndexPath* currentIndexPath = [self.collectionView indexPathForItemAtPoint:[longPressGesture locationOfTouch:0 inView:longPressGesture.view]];
        if (self.originalIndexPath != nil &&  self.originalIndexPath != currentIndexPath)
        {
            SceneCell *originalCell = (SceneCell *)[self.collectionView cellForItemAtIndexPath:self.originalIndexPath];
            originalCell.isEditOrDel = NO;
        }
        SceneCell *cell = (SceneCell *)[self.collectionView cellForItemAtIndexPath:currentIndexPath];
        cell.isEditOrDel = YES;
        self.originalIndexPath = currentIndexPath;
    }
}
- (void)enterMeController
{
    MeViewController *meVc = [[MeViewController alloc]init];
    [self.navigationController pushViewController:meVc animated:YES];
}

- (void)didTappedAddScene
{
    SceneAddController *sceneAddVc = [SceneAddController sceneAddController];
    [self.navigationController pushViewController:sceneAddVc animated:YES];
}

- (void)removeLinkage:(NSNotification *)notification
{
    debugLogInfo(@"找到了删除联动的通知！！！");
    NSInteger integerID = [notification.object integerValue];
    ZTLinkage *delLinkage = nil;
    for (ZTLinkage *lingae in self.linkages)
    {
        if (lingae.num == integerID)
        {
            debugLogInfo(@"找到了删除联动");
            delLinkage = lingae;
            break;
        }
    }
    if (delLinkage)
    {
        [self.linkages removeObject:delLinkage];
        [self.collectionView reloadData];
        [UIView animateWithDuration:0.1 animations:^{
            self.noSceneView.hidden = (self.linkages.count != 0);
        }];
    }
}

#pragma mark - DataManagerRefreshDelegate
- (void)linkageRefresh:(DataManager *)manager
{
    self.linkages = kDataManager.linkageListenList;
    dispatch_async(dispatch_get_main_queue(), ^{
        self.noSceneView.hidden = (self.linkages.count != 0);
        [self.collectionView reloadData];
    });
}

- (void)gatewayRefresh:(DataManager *)manager callbackType:(GatewayCallbackType)callbackType
{
    NSInteger linkID = kMQTTSessionManager.currentGateway.linkID;
    if (self.currentLinkmum != linkID)
    {
        self.currentLinkmum = linkID;
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.collectionView reloadData];
        });
    }
}

#pragma mark - UICollectionViewDataSource
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.linkages.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    SceneCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:sceneCellReuseIdentifier forIndexPath:indexPath];
    cell.currentLinkmum = self.currentLinkmum;
    cell.linkage = self.linkages[indexPath.item];
    cell.isEditOrDel = NO;
    __weak typeof(self)wself = self;
    cell.block = ^(SceneCellBtnFlag flag) {
        __strong typeof(wself)sself = wself;
        if (!sself)
        {
            return;
        }
        switch (flag)
        {
            case SceneCellBtnFlagEdit:
            {
                ZTLinkage *linkage = sself.linkages[indexPath.row];
                SceneEditController *editVc = [[SceneEditController alloc]init];
                editVc.linkage = linkage;
                [sself.navigationController pushViewController:editVc animated:YES];
            }
                break;
            default:
                break;
        }
    };
    return cell;
}

#pragma mark - UITableViewDelegate
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    [ZTLinkageUtil setLinkage:self.linkages[indexPath.item].num status:0];
}

#pragma mark - private method 
- (void)initSubviews
{
    self.automaticallyAdjustsScrollViewInsets = false;
    [self.view addSubview:self.navigationBar];
    [self.view addSubview:self.collectionView];
    [self.view addSubview:self.noSceneView];
    [self layoutPageSubviews];
}
- (void)layoutPageSubviews
{
    [self.navigationBar mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.leading.trailing.equalTo(self.view);
        make.height.equalTo(64);
    }];
    [self.collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.leading.trailing.equalTo(self.view);
        make.top.equalTo(self.navigationBar.bottom);
    }];
    
    [self.noSceneView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.collectionView);
    }];
}

- (void)addGesture
{
    UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPressedGestureHandle:)];
    [self.collectionView addGestureRecognizer:longPress];
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapGestureHandle:)];
    [self.collectionView addGestureRecognizer:tap];
}

- (void)initLinkage
{
    XAIGateway *currentGateway = kMQTTSessionManager.currentGateway;
    self.currentLinkmum = currentGateway.linkID;
    NSMutableArray* linkageListenList = [kDataManager.linkageListenList copy];
    NSMutableArray* linkages = [NSMutableArray array];
    for (ZTLinkage* linkage in linkageListenList)
    {
        if (linkage.gatewayApsn == kMQTTSessionManager.currentUser.currentBindApsn)
        {
            [linkages addObject:linkage];
        }
    }
    self.linkages =linkages;
    self.noSceneView.hidden = (self.linkages.count != 0);
}
#pragma mark - getters and setters
- (UICollectionViewFlowLayout *)flowLayout
{
    if (!_flowLayout)
    {
        _flowLayout = [[UICollectionViewFlowLayout alloc]init];
        _flowLayout.scrollDirection = UICollectionViewScrollDirectionVertical;
        _flowLayout.itemSize = CGSizeMake((kScreenWidth - 30) / 2, 135);
        [_flowLayout setSectionInset: UIEdgeInsetsMake(10, 10, 0, 10)];
    }
    return _flowLayout;
}
- (UICollectionView *)collectionView
{
    if (!_collectionView)
    {
        _collectionView = [[UICollectionView alloc]initWithFrame:CGRectZero collectionViewLayout:self.flowLayout];
        _collectionView.showsVerticalScrollIndicator = NO;
        _collectionView.showsHorizontalScrollIndicator = NO;
        [_collectionView registerClass:[SceneCell class] forCellWithReuseIdentifier:sceneCellReuseIdentifier];
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        _collectionView.backgroundColor = kBgColor;
    }
    return _collectionView;
}
- (NSMutableArray <ZTLinkage *>*)linkages
{
    if (!_linkages)
    {
        _linkages = [NSMutableArray array];
    }
    return _linkages;
}


- (NoSceneView *)noSceneView
{
    if (!_noSceneView)
    {
        _noSceneView = [[NoSceneView alloc]init];
        __weak typeof(self) wself = self;
        _noSceneView.addSceneClickBlock = ^() {
            __strong typeof(wself)sself = wself;
            if (!sself){
                return ;
            }
            [sself didTappedAddScene];
        };
    }
    return _noSceneView;
}

- (UINavigationBar *)navigationBar
{
    if (!_navigationBar) {
        _navigationBar = [[UINavigationBar alloc]init];
        [_navigationBar setBackgroundImage:[UIImage imageNamed:@"navigationBarbackgroundImage"] forBarMetrics:UIBarMetricsDefault];
        NSMutableDictionary *barTextAttrs = [NSMutableDictionary dictionary];
        barTextAttrs[NSForegroundColorAttributeName] = [UIColor whiteColor];
        barTextAttrs[NSFontAttributeName] = [UIFont systemFontOfSize:17];
        [_navigationBar setTitleTextAttributes:barTextAttrs];
        _navigationBar.items = @[self.titleItem];
    }
    return _navigationBar;
}
- (UINavigationItem *)titleItem
{
    if (!_titleItem) {
        _titleItem = [[UINavigationItem alloc]init];
        _titleItem.leftBarButtonItem = [UIBarButtonItem createBarbuttonItem:@"home_icon_me" target:self action:@selector(enterMeController)];
        _titleItem.rightBarButtonItem =  [UIBarButtonItem createBarbuttonItem:@"security_add" target:self action:@selector(didTappedAddScene)];
        _titleItem.title = @"智能场景";
    }
    return _titleItem;
}

@end
